In SQL, the MIN()
and MAX()
functions are aggregate functions used to find the minimum and maximum values respectively within a set of values. These functions are often used in combination with the SELECT
statement to retrieve the smallest or largest value from a specific column, or in combination with the GROUP BY
clause to find the smallest or largest value for each group.
Here's how the MIN()
and MAX()
functions are used:
Using MIN()
function:
MIN(column_name)
SELECT MIN(salary) FROM employees;
salary
column in the employees
table.Using MAX()
function:
MAX(column_name)
SELECT MAX(salary) FROM employees;
salary
column in the employees
table.Additionally, you can use the MIN()
and MAX()
functions with a GROUP BY
clause to find the minimum or maximum value for each group in the result set. This is particularly useful when you want to find the minimum or maximum value within different categories.
Here's an example of using MIN()
and MAX()
with GROUP BY
:
SELECT department_id, MIN(salary) AS min_salary, MAX(salary) AS max_salary
FROM employees
GROUP BY department_id;
In this example, the query will return the minimum and maximum salary for each department_id
from the employees
table.
Remember, the MIN()
and MAX()
functions are useful for finding extreme values within a dataset and are often used in data analysis and reporting tasks.